package com.shycloud.mido.member.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.member.api.entity.*;
import com.shycloud.mido.member.api.vo.MemberDetailForLoginVO;
import com.shycloud.mido.member.service.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 密码登录获取用户信息
 *
 * @author nianhua.jiang
 * @date 2020/6/24 16:03
 */
@Slf4j
@Component("PWD")
@AllArgsConstructor
public class PwdLoginHandler extends AbstractLoginHandler {

	/** 会员模块 service */
	private final MemberServiceV2 memberService;
	/** 教师模块 service */
	private final OrgTeacherDetailedService teacherDetailedService;
	/** 学生模块 service */
	private final OrgStudentDetailedService studentDetailedService;
	/** 机构模块 service */
	private final OrgOrganizationService orgOrganizationService;
	/** redis 缓存 */
	private final RedisTemplate redisTemplate;

	/**
	 * 传入为用户名
	 * 不用处理
	 *
	 * @param username
	 * @return
	 */
	@Override
	public String identify(String username) {
		return username;
	}

	/**
	 * 通过username 获取用户信息
	 *
	 * @param username
	 * @return
	 */
	@Override
	public MemberDetailForLoginVO info(String username) {

		//查询用户信息
		MemberDetailForLoginVO member = memberService.getUserDetail(username);

		//用户不存在
		if (member == null) {
			log.info("未查询到用户名:{}", username);
			return null;
		}

		//身份为教师
		if ("1".equals(member.getIsTeacher())) {
			//查询教师表，获取默认机构ID
			List<OrgTeacherDetailed> teacherDetaileds = teacherDetailedService.list(new QueryWrapper<OrgTeacherDetailed>()
					.eq(OrgTeacherDetailed.COL_MEMBER_ID, member.getId())
					.and(x -> x.eq(OrgTeacherDetailed.COL_DEL_FLAG, "0"))
					.orderByAsc(OrgTeacherDetailed.COL_CREATE_TIME));

			if (teacherDetaileds.size() == 0) {
				log.info("未查询到所在机构，用户名为:{}", username);
				return null;
			} else {
				//获取机构信息
				OrgOrganization org = orgOrganizationService.getById(teacherDetaileds.get(0).getOrgId());
				//机构ID
				member.setOrgId(org.getId());
				//机构名
				member.setOrgName(org.getName());
			}

		}

		//身份为学生
		else {

			//查询学生表，获取默认机构ID
			List<OrgStudentDetailed> studentDetaileds = studentDetailedService.list(new QueryWrapper<OrgStudentDetailed>()
					.eq(OrgStudentDetailed.COL_MEMBER_ID, member.getId())
					.and(x -> x.eq(OrgStudentDetailed.COL_DEL_FLAG, "0"))
					.orderByAsc(OrgStudentDetailed.COL_CREATE_TIME));

			if (studentDetaileds.size() > 0) {
				if (studentDetaileds.get(0).getOrgId() != 0) {
					//获取机构信息
					OrgOrganization org = orgOrganizationService.getById(studentDetaileds.get(0).getOrgId());
					//机构ID
					member.setOrgId(org.getId());
					//机构名
					member.setOrgName(org.getName());
				} else {
					//机构ID
					member.setOrgId(0);
					//机构名
					member.setOrgName("暂无机构");
				}
			} else {

				//false 代表 redis 有这个键就不能继续操作了
				Boolean saveStudentRedis = redisTemplate.opsForValue().setIfAbsent("saveStudent_" + member.getId(), "1", 5, TimeUnit.SECONDS);
				if (saveStudentRedis) {
					//新建学生身份，orgId 为 0，暂无机构
					//创建学生用户
					OrgStudentDetailed student = new OrgStudentDetailed();
					//memberId
					student.setMemberId(member.getId());
					//机构ID
					student.setOrgId(0);
					//创建时间
					student.setCreateTime(new Date());
					//逻辑删除
					student.setDelFlag(CommonConstants.STATUS_NORMAL);
					//昵称
					student.setName(member.getShowname());
					studentDetailedService.save(student);
				}
				//机构ID
				member.setOrgId(0);
				//机构名
				member.setOrgName("暂无机构");
			}
		}
		return member;
	}
}
